package com.otod.pm.prj.service;


import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Lists;
import com.otod.base.exception.AppException;
import com.otod.base.service.BaseService;
import com.otod.commons.utils.BeanUtils;
import com.otod.commons.utils.BizCodeUtil;
import com.otod.commons.utils.DateUtils;
import com.otod.commons.utils.StringUtils;
import com.otod.pm.comment.service.SubmitInfoService;
import com.otod.pm.comment.vo.AsmgSubmitInfoVo;
import com.otod.pm.constants.PmConstant;
import com.otod.pm.prj.bo.TaskCalendarBo;
import com.otod.pm.prj.bo.TaskFileBo;
import com.otod.pm.prj.mapper.TaskMapper;
import com.otod.pm.prj.vo.PmTaskEmpVo;
import com.otod.pm.prj.vo.StepVo;
import com.otod.pm.prj.vo.TaskTpVo;
import com.otod.pm.prj.vo.TaskVo;
import com.otod.sys.amcm.MessageConstant;
import com.otod.sys.amcm.service.AmcmMsgAppService;
import com.otod.sys.emp.service.IEmpService;
import com.otod.sys.vo.AuapTEmpVo;


/**
 * 任务管理
 * @author jqiu
 */
@Service
@Transactional(readOnly=true)
public class TaskService extends BaseService {
	
	@Autowired
	TaskMapper taskMapper;
	
	@Autowired
	 private ProjectService projectService;
	
	@Autowired
	private AmcmMsgAppService msgService;
	
	@Autowired
	private PmTaskEmpService taskEmpService;
	
	@Autowired
	TaskTpService taskTpService;
	
	@Autowired
	StepService stepService;
	
	 @Autowired
	IEmpService empService;
	
	 @Autowired
	PmStepDocCfgService pmStepDocCfgService;
	 
	 @Autowired
	 SubmitInfoService submitInfoService;
		
	/***
	 * 新增任务
	 * @param taskVo
	 */
	@Transactional
	public TaskVo insert(TaskVo taskVo) {
		taskVo.setUuid(super.getUUID());
		StepVo stepVo = stepService.getById(taskVo.getStepId());
		Date date = stepVo.getStartDate();
		
		
		if(date!=null&&(date.getTime()>DateUtils.getCurrentDate().getTime())){
			taskVo.setStartDate(date);
			taskVo.setStatus(PmConstant.TASK_STATUS_READY);
		}else if(date==null){
			taskVo.setStatus(PmConstant.TASK_STATUS_READY);
		}else if(date.getTime()<DateUtils.getCurrentDate().getTime()){
			taskVo.setStartDate(DateUtils.getCurrentDate());
			taskVo.setStatus(PmConstant.TASK_STATUS_STARTING);
		}
		
		String prjStatus = projectService.getById(taskVo.getPrjId()).getStatus();
		if(StringUtils.isEmpty(taskVo.getEmpNo())){
			taskVo.setStatus(PmConstant.TASK_STATUS_READY);
		}else{
			if(null == taskVo.getStartDate() || taskVo.getStartDate().getTime()>DateUtils.getCurrentDate().getTime()){				
				taskVo.setStatus(PmConstant.TASK_STATUS_READY);
			}else if(PmConstant.PRJ_STATUS_STARTING.equals(prjStatus)){
				taskVo.setStatus(PmConstant.TASK_STATUS_STARTING);
			}else{
				taskVo.setStatus(PmConstant.TASK_STATUS_READY);
			}
		}
		
		taskMapper.insert(taskVo);
		if(!StringUtils.isEmpty(taskVo.getEmpNo())){
			
			//加入主要人员信息，加入协作人员信息
			PmTaskEmpVo taskEmpVo = new PmTaskEmpVo();
			taskEmpVo.setTaskId(taskVo.getUuid());
			taskEmpVo.setEmpNo(taskVo.getEmpNo());
			taskEmpVo.setRoleType(1);
			taskEmpVo.setPrjId(taskVo.getPrjId());
			taskEmpService.add(taskEmpVo);
			
			if(!StringUtils.isEmpty(taskVo.getEmpNos())){
				String[] attr = taskVo.getEmpNos().split(",");
				for (String str : attr) {
					taskEmpVo = new PmTaskEmpVo();
					taskEmpVo.setTaskId(taskVo.getUuid());
					taskEmpVo.setEmpNo(str);
					taskEmpVo.setPrjId(taskVo.getPrjId());
					taskEmpVo.setRoleType(0);
					taskEmpService.add(taskEmpVo);
					
					AuapTEmpVo empVo = empService.findByEmpNo(str);
					if(empVo != null){
						taskVo.setEmpName(empVo.getEmpName());
						msgService.installMsgVo(taskVo, MessageConstant.TASK_INSERT);// insert Vo 
					}
				}
			}
			
			
			
			
			
			AuapTEmpVo empVo = empService.findByEmpNo(taskVo.getEmpNo());
			if(empVo != null){
				taskVo.setEmpName(empVo.getEmpName());
				msgService.installMsgVo(taskVo, MessageConstant.TASK_INSERT);// insert Vo 
			}
			
			
		}
		return taskVo;
	}
	
	/**
	 * 修改
	 * @param map
	 */
	@Transactional
	public void update(Map<String, Object> map){
		String id = (String)map.get("uuid");
		TaskVo vo = this.getById(id);
		
		taskMapper.update(map);
		
		//记录日志
		super.invokeLogInsert("PM_001005", id, vo, map);	
	}
	
	/**
	 * 删除
	 * @param id
	 */
	@Transactional
	public void deleteById(String id){
		TaskVo vo = this.getById(id);
		taskMapper.deleteById(id);
		if(StringUtils.isNotEmpty(vo.getEmpNo())){
			
			msgService.installMsgVo(vo, MessageConstant.TASK_DELETE);// delete Vo
		}
	}
	
	/**
	 * 主键查询
	 * @param id
	 */
	public TaskVo getById(String id){
		return taskMapper.getById(id);
	}
	
	/**
	 * 统一查询（对BO对象进行处理）
	 * @param param
	 * @return
	 */
	private List<TaskVo> queryForList(Map<String,Object> param){
		List<TaskVo> list = taskMapper.queryForList(param);
		for (TaskVo taskVo : list) {
			taskVo.setEndDateFormat(DateUtils.formatDate(taskVo.getEndDate(),"yyyy-MM-dd"));
			taskVo.setStartDateFormat(DateUtils.formatDate(taskVo.getStartDate(), "yyyy-MM-dd"));
			taskVo.setStatusName(BizCodeUtil.getBizCodeNameByNo("pmTaskType", taskVo.getStatus()));
		}
		return list;
	}
	
	public List<TaskVo> queryTaskList(Map<String,Object> param){
		return taskMapper.queryForList(param);
	}
	
	/**
	 * 通过人员编号查询
	 * @param empNo
	 */
	public List<TaskVo> findByEmpNo(String empNo){
		Map<String,Object> param = new HashMap<String, Object>();
		param.put("empNo",empNo);
		return queryForList(param);
	}
	
	/**
	 * 查询产品下所有有效果的任务
	 * @param stepId 阶段ID
	 */
	public List<TaskVo> queryValidList(String stepId){
		Map<String,Object> param = new HashMap<String, Object>();
		param.put("stepId",stepId);
		List<TaskVo> list = queryForList(param);
		for (TaskVo taskVo : list) {
			if(taskVo.getEndDate()==null){
				taskVo.setEndDate(taskVo.getPlanEndDate());
			}
		}
		return queryForList(param);
	}
	
	/**
	 * 
	 * 通过 用户的number 和 项目的状态查询 正在进行的项目   
	 * @param empNo  用户的naumber
	 * @param status  项目的状体 
	 * @return
	 */
	public List<TaskVo> queryListStatus(String empNo,String status){
		Map<String, Object> param = new HashMap<String,Object>();
		param.put("empNo", empNo);
		param.put("status", status);
		return queryForList(param);
	}
	
	/**
	 * 通过模板生成项目阶段
	 * @param prjId
	 * @param stepId
	 * @param tpId
	 * @throws AppException
	 */
	@Transactional
	public void createPrjTaskByTemplate(String prjId,String stepTpId,String stepId,String tpId,TaskVo vo){
		
		
		
		List<TaskTpVo> list = Lists.newArrayList();
		list = taskTpService.queryTpIdList(stepTpId);
		TaskVo taskVo;
		for (TaskTpVo taskTpVo : list) {
			taskVo = new TaskVo();
			BeanUtils.copyProperties(taskTpVo,taskVo);
			taskVo.setPrjId(prjId);
			taskVo.setStepId(stepId);
			taskVo.setCreateDt(DateUtils.getCurrentDate());
			taskVo.setCreateEmp(vo.getCreateEmp());
			taskVo.setCreateEmpNo(vo.getCreateEmpNo());
			taskVo.setCreateIpaddr(vo.getCreateIpaddr());
			taskVo.setCreateOrg(vo.getCreateOrg());
			taskVo.setCreateOrgNo(vo.getCreateOrgNo());
			this.insert(taskVo);
		}
	}
	
	/**
	 * 设置任务状态
	 * @param vo staus
	 * return TaskVo
	 */
	@Transactional
	public void changeTaskStatus(String taskId,String status,AsmgSubmitInfoVo submitVo){
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("uuid", taskId);
		map.put("status", status);
		TaskVo vo = this.getById((String)map.get("uuid"));
		
		if(status == PmConstant.TASK_STATUS_COMMIT){
			map.put("endDate", DateUtils.getCurrentDate());
			if(vo !=null){
				vo.setEmpNo(vo.getCreateEmpNo());
				vo.setEmpName(vo.getCreateEmp());
				msgService.installMsgVo(vo, MessageConstant.TASK_SUBMIT);
			}
		}
		if(status == PmConstant.TASK_STATUS_STARTING){
			map.put("endDate", null);
			if(vo !=null){
				msgService.installMsgVo(vo, MessageConstant.TASK_TOBACK);
			}
		}
		if(submitVo != null){
			submitInfoService.addTp(submitVo);
		}
		this.update(map);
	}
	
	/**
	 * 设置任务状态
	 * @param vo staus
	 * return TaskVo
	 */
	@Transactional
	public void changeTaskStatus(Map<String,Object> map,Map<String,Object> params,String message){
		
		submitInfoService.updateTp(params);
		
		this.update(map);
		TaskVo vo = this.getById((String)map.get("uuid"));
		
		if(vo !=null){
			msgService.installMsgVo(vo, message);
		}
		
	}
	
	/**
	 * 查询时间范围内的任务
	 * @param startTime
	 * @param endTime
	 * @return
	 */
	public List<TaskCalendarBo> queryTaskCalendar(Date startTime,Date endTime,String empNo){
		Map<String, Object> map = new HashMap<String,Object>();
		map.put("actualStartDate", startTime);
		map.put("actualEndDate", endTime);
		map.put("empNo", empNo);
		List<TaskVo> indexBoList = Lists.newArrayList();
		//封装数据
		List<TaskCalendarBo> indexBos = Lists.newArrayList();
		TaskCalendarBo TaskCalendarBo = null;
		indexBoList = taskMapper.queryForList(map);
		for (TaskVo taskVo : indexBoList) {
			TaskCalendarBo = new TaskCalendarBo();
			//准备中
			if (PmConstant.TASK_STATUS_READY.equals(taskVo.getStatus())) {
				//计划开始时间
				TaskCalendarBo.setStartTime(taskVo.getStartDate());
				if(taskVo.getPlanEndDate()!=null){
					//计划时间大于本月最后一天时间
					if(DateUtils.getDaysBetweenTwoDates(DateUtils.formatDate(taskVo.getPlanEndDate(),"yyyyMMdd"), DateUtils.formatDate(endTime,"yyyyMMdd"))<0){
					     //实际时间
					     TaskCalendarBo.setEndTime(taskVo.getPlanEndDate());
					     //结束时间
					     //TaskCalendarBo.setEndTime(endTime);
					//计划时间小于本月最后一天
					}else{
						TaskCalendarBo.setEndTime(taskVo.getPlanEndDate());
					}
				//计划开始时间为空
				}else{
						//显示结束时间
					//TaskCalendarBo.setEndTime(taskVo.getEndDate().getDay());
					TaskCalendarBo.setEndTime(taskVo.getPlanEndDate());
				}
				//得到标题
				TaskCalendarBo.setTitle(taskVo.getTaskName());
				//设置样式
				TaskCalendarBo.setClassName("label-info");
			//任务进行中	
			}else if(PmConstant.TASK_STATUS_STARTING.equals(taskVo.getStatus())||PmConstant.TASK_STATUS_BEBACK.equals(taskVo.getStatus())){
				//设置开始时间  和计划结束时间
				TaskCalendarBo.setStartTime(taskVo.getStartDate());
				if(taskVo.getEndDate()!=null){
					if(DateUtils.getDaysBetweenTwoDates(DateUtils.formatDate(taskVo.getEndDate(),"yyyyMMdd"), DateUtils.formatDate(endTime,"yyyyMMdd"))<0){
						//实际时间
					    // TaskCalendarBo.setActualEndTime(taskVo.getPlanEndDate());
					     //结束时间
						TaskCalendarBo.setEndTime(endTime);
					}else{
						TaskCalendarBo.setEndTime(taskVo.getEndDate());
					}
				}else{
					TaskCalendarBo.setEndTime(taskVo.getPlanEndDate());
				}
				//得到标题
				TaskCalendarBo.setTitle(taskVo.getTaskName());
				TaskCalendarBo.setClassName("label-danger");
				
			//任务终止
			}else if(PmConstant.TASK_STATUS_COMMIT.equals(taskVo.getStatus())){
				
			//任务结项	
			}
			/*else if(PmConstant.TASK_STATUS_FLISH.equals(taskVo.getStatus())){
				//设置开始时间
				TaskCalendarBo.setStartTime(taskVo.getStartDate());
				//结束时间
				TaskCalendarBo.setEndTime(taskVo.getEndDate());
				//得到标题
				TaskCalendarBo.setTitle(taskVo.getTaskName());
				//设置样式
				TaskCalendarBo.setClassName("label-success");
			}*/
			
			
			indexBos.add(TaskCalendarBo);
		}
		
		return  indexBos;
	}
	
	/**
	 * 通过stepId查询数据
	 * @param stepId
	 * @return
	 */
	public List<TaskFileBo> selectStepId(String stepId){
		List<TaskFileBo> taskFileBo =Lists.newArrayList();
		
		taskFileBo = taskMapper.selectStepId(stepId);		
		//重新分装数据
		return taskFileBo;
	}
	/**
	 * 通过项目查询任务相关信息
	 * @param prjId
	 * @return
	 */
	public List<TaskVo> selectProjectTask(String prjId){
		List<TaskVo> list = new ArrayList<TaskVo>();
		Map<String, Object> map = new HashMap<String,Object>();
		map.put("prjId", prjId);
		list = taskMapper.queryForList(map);
		return list;
	}
	
	
	/**
	 * 逻辑删除 项目对应的任务信息
	 * @param map
	 */
	@Transactional
	public void remove(Map<String, Object> map) {
		taskMapper.remove(map);
	}
}
